package uicgas.register.GUI;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.JButton;

import uicgas.globaldata.ActivationData;
import uicgas.globaldata.ControlMessage;
import uicgas.globaldata.CreditCard;
import uicgas.globaldata.Messages;
import uicgas.globaldata.Password;
import uicgas.globaldata.Pump;
import uicgas.globaldata.PumpState;
import uicgas.globaldata.SelfAnnouncement;
import uicgas.globaldata.States;
import uicgas.globaldata.Transaction;
import uicgas.globaldevice.MockCardReader;
import uicgas.register.RegisterLogic;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;

public class PumpSelectionScreen extends JFrame
{

	private JPanel contentPane;
	private PumpSelectionScreen thisScreen;
	private int pumpidnum;
	private String password;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args)
	{

		CreditCard Card = new CreditCard("Halm", "0000000000000000000", null);
		Transaction newTransaction = new Transaction(9.20, 2.345, Card);
		final Pump pumptemp = new Pump(10, newTransaction, 11.00,
				States.DEACTIVATED);

		EventQueue.invokeLater(new Runnable()
		{
			public void run()
			{
				try
				{
					if (pumptemp.getID() < 20 && pumptemp.getID() >= 0)
					{
						//						PumpSelectionScreen frame = new PumpSelectionScreen(
						//								pumptemp);
						//						frame.setVisible(true);
					}
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public PumpSelectionScreen(final Pump pumpid, final RegisterLogic Register)
	{
		setResizable(false);
		pumpidnum = pumpid.getID() + 1;
		thisScreen = this;
		setTitle("UIC Gas - Pump No: " + pumpidnum + " Actions");
		setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		setBounds(100, 100, 500, 500);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		JLabel PumpSelectionScreen = new JLabel(
				"Please select an action to perform for pump number "
						+ pumpidnum + ".");
		//JLabel PumpSelectionScreen = new JLabel("Please select an action to perform for pump number " + pumpid + ".");
		PumpSelectionScreen.setHorizontalAlignment(SwingConstants.CENTER);
		PumpSelectionScreen.setFont(new Font("Tahoma", Font.BOLD, 14));
		PumpSelectionScreen.setBounds(10, 11, 464, 48);
		contentPane.add(PumpSelectionScreen);

		JButton btnPrepay = new JButton("Prepay");
//		btnPrepay.setEnabled(true);
		if (pumpid.getState() == States.ACTIVATED
				|| pumpid.getState() == States.DECOMMISSIONED)
		{
			btnPrepay.setEnabled(false);
		}
		btnPrepay.addMouseListener(new MouseAdapter()
		{
			@Override
			public void mouseClicked(MouseEvent e)
			{
				Double Ammount = -1.00;
				boolean flag1 = false;
				boolean flag2 = false;
				thisScreen.setAlwaysOnTop(false);
				if (JOptionPane.showConfirmDialog(null,
						"Would you like to pay with a Creditcard?",
						"UIC Gas - Creditcard Option",
						JOptionPane.YES_NO_OPTION) == 0)
				{
					JOptionPane.showMessageDialog(null,
							"Please Slide Credit Card Now.",
							"UIC Gas - CreditCard", JOptionPane.PLAIN_MESSAGE);
					//Pause(1);
					JOptionPane.showMessageDialog(null,
							"Validating Card Now.\nPlease wait.",
							"UIC Gas - Validating Card",
							JOptionPane.INFORMATION_MESSAGE);
					//Pause(1);
					MockCardReader newCard = new MockCardReader();

					CreditCard myCard = newCard.getCardData();//need to get credit card infor here.
					Register.validateCardInfo(myCard, pumpid);
					Pause(1);
					if (Register.getCardValidity())
					{
						if (JOptionPane.showConfirmDialog(null,
								"Activate Pump No. " + pumpidnum
										+ " and the creditcard?",
								"UIC Gas - Activate Pump",
								JOptionPane.OK_CANCEL_OPTION) == 0)
						{
							JOptionPane.showMessageDialog(null,
									"Activating Pump No. " + pumpidnum + ".",
									"UIC Gas - Activate Pump",
									JOptionPane.PLAIN_MESSAGE);
							ActivationData myActData2 = new ActivationData(
									pumpidnum - 1, 0.00, myCard);
							ControlMessage messageOut2 = new ControlMessage(
									Messages.ACTIVATEPUMP, myActData2);
							Register.getCommunication().sendData(messageOut2);
						}
					}
					else
					{
						JOptionPane
								.showMessageDialog(
										null,
										"There was an error validating the credit card",
										"UIC Gas - Card Validation",
										JOptionPane.ERROR_MESSAGE);
					}
				}
				else
				{
					while (Ammount == -1.00)
					{
						Ammount = Register.inputDollarAmmount();
						if (JOptionPane.showConfirmDialog(null,
								"Is the following amount correct $" + Ammount
										+ "?", "UIC Gas - Verify $ Amount",
								JOptionPane.OK_CANCEL_OPTION) == 0)
						{
							flag1 = true;
							pumpid.setPrepaid(Ammount);
							if (JOptionPane.showConfirmDialog(null,
									"Ready to Activate Pump No. " + pumpidnum
											+ " with the following amount $"
											+ Ammount + "?",
									"UIC Gas - Activate Pump",
									JOptionPane.OK_CANCEL_OPTION) == 0)
							{
								flag2 = true;
							}
							else
							{
								exitThisScreen();
							}
						}
						if (flag1 == true && flag2 == true)
						{
							JOptionPane.showMessageDialog(null,
									"Activating Pump No. " + pumpidnum + ".",
									"UIC Gas - Activate Pump",
									JOptionPane.PLAIN_MESSAGE);
							ActivationData myActData = new ActivationData(
									pumpidnum - 1, Ammount, null);
							ControlMessage messageOut = new ControlMessage(
									Messages.ACTIVATEPUMP, myActData);
							Register.getCommunication().sendData(messageOut);
						}
					}
				}
				thisScreen.setAlwaysOnTop(true);
				exitThisScreen();
			}
		});
		btnPrepay.setFont(new Font("Tahoma", Font.BOLD, 18));
		btnPrepay.setBounds(50, 70, 100, 50);
		contentPane.add(btnPrepay);

		JButton btnDecommisionPump = new JButton("Decommision Pump");
		if (pumpid.getState() == States.ACTIVATED
				|| pumpid.getState() == States.DECOMMISSIONED)
		{
			btnDecommisionPump.setEnabled(false);
		}
		btnDecommisionPump.addMouseListener(new MouseAdapter()
		{
			@Override
			public void mouseClicked(MouseEvent e)
			{
				if (JOptionPane.showConfirmDialog(null,
						"Are you sure that you want to decommission pump "
								+ pumpidnum + "?",
						"UIC Gas - Decommission pump " + pumpid.getID(),
						JOptionPane.OK_CANCEL_OPTION) == 0)
				{
					SelfAnnouncement pumpState = new SelfAnnouncement(Register
							.getID(), pumpid.getID());
					ControlMessage messageOut = new ControlMessage(
							Messages.DECOMMISSIONPUMP, pumpState);
					Register.getCommunication().sendData(messageOut); //uncomment when Communications is fixed //FIXME
					exitThisScreen();
				}
				else
				{
					//do nothing
				}
			}
		});
		btnDecommisionPump.setFont(new Font("Tahoma", Font.BOLD, 18));
		btnDecommisionPump.setBounds(50, 131, 250, 50);
		contentPane.add(btnDecommisionPump);

		JButton btnRecommissionPump = new JButton("Recommission Pump");
		if (pumpid.getState() == States.ACTIVATED
				|| pumpid.getState() == States.DEACTIVATED)
		{
			btnRecommissionPump.setEnabled(false);
		}
		btnRecommissionPump.addMouseListener(new MouseAdapter()
		{
			@Override
			public void mouseClicked(MouseEvent e)
			{
				//String inPassword = JOptionPane.showInputDialog(null, "Please Provide the needed password for recommissioning the pump.", "InputPasword", JOptionPane.INFORMATION_MESSAGE);
				//StartPassword Screen
				startPasswordScreen(Register, pumpid);
				exitThisScreen();
			}
		});
		btnRecommissionPump.setFont(new Font("Tahoma", Font.BOLD, 18));
		btnRecommissionPump.setBounds(50, 192, 250, 50);
		contentPane.add(btnRecommissionPump);

		JButton btnDeactivatePump = new JButton("Deactivate Pump");
		if (pumpid.getState() == States.DEACTIVATED
				|| pumpid.getState() == States.DECOMMISSIONED)
		{
			btnDeactivatePump.setEnabled(false);
		}
		btnDeactivatePump.addMouseListener(new MouseAdapter()
		{
			@Override
			public void mouseClicked(MouseEvent e)
			{

				if (JOptionPane.showConfirmDialog(null,
						"Are you sure that you want to Deactivate pump "
								+ pumpidnum + "?", "UIC Gas - Deactivate pump "
								+ pumpid.getID(), JOptionPane.OK_CANCEL_OPTION) == 0)
				{
					SelfAnnouncement pumpState = new SelfAnnouncement(Register
							.getID(), pumpid.getID());
					ControlMessage messageOut = new ControlMessage(
							Messages.DEACTIVATEPUMP, pumpState);
					Register.getCommunication().sendData(messageOut);//uncomment when communications is fixed //FIXME
					exitThisScreen();
				}
				else
				{
					//do nothing
				}
			}
		});
		btnDeactivatePump.setFont(new Font("Tahoma", Font.BOLD, 18));
		btnDeactivatePump.setBounds(50, 253, 250, 50);
		contentPane.add(btnDeactivatePump);

		JButton btnPrintReceipt = new JButton("Print Receipt");
		btnPrintReceipt.addMouseListener(new MouseAdapter()
		{
			@Override
			public void mouseClicked(MouseEvent e)
			{
				JOptionPane.showMessageDialog(null, "Now Printing receipt",
						"Print Receipt", 0);
				if (pumpid.getTransaction() != null)
				{
					JOptionPane.showMessageDialog(null, pumpid.getTransaction()
							.toPrint(), "RECEIPT", 0);
				}
				else
				{
					JOptionPane
							.showMessageDialog(
									null,
									"There was an error while printing the requested receipt.",
									"UIC Gas - Receipt Error",
									JOptionPane.ERROR_MESSAGE);
				}
				exitThisScreen();
			}
		});
		btnPrintReceipt.setFont(new Font("Tahoma", Font.BOLD, 18));
		btnPrintReceipt.setBounds(50, 314, 200, 50);
		contentPane.add(btnPrintReceipt);

		JButton btnCalculateChangeDue = new JButton("Calculate Change Due");
		btnCalculateChangeDue.addMouseListener(new MouseAdapter()
		{
			@Override
			public void mouseClicked(MouseEvent e)
			{
				SelfAnnouncement self = new SelfAnnouncement(Register.getID(),
						pumpid.getID());
				ControlMessage myMessage = new ControlMessage(
						Messages.ANNOUNCEALLCONNECTEDPUMPS, self);
				Register.getCommunication().sendData(myMessage);
				Pause(2);
				calculateChangeDue(pumpid, Register);
				exitThisScreen();
			}
		});
		btnCalculateChangeDue.setFont(new Font("Tahoma", Font.BOLD, 18));
		btnCalculateChangeDue.setBounds(50, 375, 250, 50);
		contentPane.add(btnCalculateChangeDue);

		JButton btnBack = new JButton("Back");
		btnBack.addMouseListener(new MouseAdapter()
		{
			@Override
			public void mouseClicked(MouseEvent arg0)
			{
				//set the visibility of the previous screen to true then set this screen to false or destroy the screen.
				exitThisScreen();
			}
		});
		btnBack.setBounds(385, 428, 89, 23);
		contentPane.add(btnBack);
	}

	protected void startPasswordScreen(RegisterLogic register, Pump pump)
	{
		PasswordEntry pwdScreen = new PasswordEntry(this, register, pump);
		String password = "";
		pwdScreen.setAlwaysOnTop(true);
		pwdScreen.setVisible(true);
		Pause(2);
		//		pwdScreen
		//		if(register.getPasswordValidity())
		//		{
		//			SelfAnnouncement myAnouncment = new SelfAnnouncement(register.getID(), pumpidnum-1);
		//			ControlMessage myMessage = new ControlMessage(Messages.RECOMMISSIONPUMP, myAnouncment);
		//			register.getCommunication().sendData(myMessage);
		//		}
		//		else
		//		{
		//			pwdScreen.dispose();
		//		}

	}

	private void exitThisScreen()
	{
		this.dispose();
	}

	public String Password(String password)
	{
		this.password = password;
		return password;
	}

	private void calculateChangeDue(Pump currentPump, RegisterLogic register)
	{
		int pumpID = currentPump.getID();
		Transaction currentTransaction = register.allPumps[currentPump.getID()]
				.getTransaction();
		if (currentTransaction != null)
		{
			double finalAmount = currentTransaction.getFinalDollars();
			double initialAmount = currentPump.getPrepaidAmount();
			double change = initialAmount - finalAmount;
			change = Math.abs(change);

			if (finalAmount > initialAmount)
			{
				//The Customer owes more money for some reason
				JOptionPane
						.showMessageDialog(
								null,
								"The Customer has pumped more than they have paid for \nplease have the customer pay the following amount:\n$"
										+ change, "Charge Customer Warrning",
								JOptionPane.WARNING_MESSAGE);
			}
			else if (finalAmount == initialAmount)
			{
				//the amount paid is the amount pumps no change is due
				JOptionPane.showMessageDialog(null,
						"No Change is due at this time.", "Change Due",
						JOptionPane.INFORMATION_MESSAGE);
			}
			else if (finalAmount < initialAmount)
			{
				//the amount paid is more than the amount pumped and change is due.
				JOptionPane
						.showMessageDialog(
								null,
								"There is change due to the customer.\nPlease provide the following amount to the customer:\n$"
										+ change, "Change Due",
								JOptionPane.INFORMATION_MESSAGE);
			}
		}
		else
		{
			JOptionPane.showMessageDialog(null,
					"There was an Error while Calculating the needed change.",
					"UIC Gas - Change Error", JOptionPane.ERROR_MESSAGE);
		}
	}

	/**
	 * Used to provide a pauseing action to the system.
	 * @author Steve
	 * @param iTimeInSeconds, input in integers the time in which the system is to pause
	 */
	private void Pause(int iTimeInSeconds)
	{
		long time_start, time_end;

		time_start = System.currentTimeMillis();
		time_end = System.currentTimeMillis() + (iTimeInSeconds * 1000);

		do
		{
			time_start = System.currentTimeMillis();

		}
		while (time_start < time_end);
		{
			//do nothing, just wait
		}
	}

}
